<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="header">
			<text class="header-title">我的订单</text>
		</view>

		<!-- 订单状态筛选 -->
		<view class="filter-tabs">
			<view
				class="tab-item"
				:class="{ active: currentTab === 'all' }"
				@click="switchTab('all')"
			>
				<text class="tab-text">全部</text>
			</view>
			<view
				class="tab-item"
				:class="{ active: currentTab === 'pending_payment' }"
				@click="switchTab('pending_payment')"
			>
				<text class="tab-text">待支付</text>
			</view>
			<view
				class="tab-item"
				:class="{ active: currentTab === 'in_progress' }"
				@click="switchTab('in_progress')"
			>
				<text class="tab-text">进行中</text>
			</view>
			<view
				class="tab-item"
				:class="{ active: currentTab === 'completed' }"
				@click="switchTab('completed')"
			>
				<text class="tab-text">已完成</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list" v-if="!loading">
			<!-- 有订单时显示列表 -->
			<view v-if="filteredOrders.length > 0">
				<view
					class="order-item"
					v-for="order in filteredOrders"
					:key="order.id"
					@click="viewOrderDetail(order)"
				>
					<view class="order-header">
						<view class="order-info">
							<text class="parking-name">{{ order.parking_lot_name || '停车场' }}</text>
							<text class="order-number">订单号：{{ order.order_number }}</text>
						</view>
						<view class="order-status">
							<text class="status-text" :class="getStatusClass(order.status)">
								{{ getStatusText(order.status) }}
							</text>
						</view>
					</view>

					<view class="order-details">
						<view class="detail-row">
							<text class="detail-label">车牌号：</text>
							<text class="detail-value">{{ order.license_plate }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">停车类型：</text>
							<text class="detail-value parking-type" :class="order.parking_type">
								{{ order.parking_type === 'outdoor' ? '🌤️ 室外停车' : '🏠 室内停车' }}
							</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">预计时间：</text>
							<text class="detail-value">{{ formatOrderTime(order.planned_start_time, order.planned_end_time) }}</text>
						</view>
						<view class="detail-row">
							<text class="detail-label">应付金额：</text>
							<text class="detail-value price">¥{{ order.final_amount }}</text>
						</view>
					</view>

					<view class="order-actions" v-if="order.status === 'pending_payment'">
						<button class="action-btn cancel-btn" @click.stop="cancelOrder(order)">取消订单</button>
						<button class="action-btn pay-btn" @click.stop="payOrder(order)">立即支付</button>
					</view>
				</view>
			</view>

			<!-- 无订单时显示空状态 -->
			<view v-else class="empty-state">
				<view class="empty-content">
					<text class="empty-text">{{ getEmptyText() }}</text>
					<button class="go-booking-btn" @click="goBooking">立即预定</button>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-state">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getUserOrders } from '../../api/user.js'
import { cancelParkingOrder } from '../../api/parking.js'
import { initiatePayment, getUserOpenid } from '../../utils/payment.js'

// 响应式数据
const currentTab = ref<string>('all')
const orders = ref<any[]>([])
const loading = ref<boolean>(false)

// 计算属性 - 由于后端已经根据状态筛选，这里直接返回所有数据
const filteredOrders = computed(() => {
	return orders.value
})

// 切换标签
const switchTab = (tab: string) => {
	currentTab.value = tab
	// 切换标签时重新加载数据
	loadOrders()
}

// 获取状态文本
const getStatusText = (status: string) => {
	const statusMap: Record<string, string> = {
		'pending_payment': '待支付',
		'in_progress': '进行中',
		'pending_additional_payment': '待补款',
		'completed': '已完成',
		'cancelled': '已取消'
	}
	return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status: string) => {
	const classMap: Record<string, string> = {
		'pending_payment': 'status-pending',
		'in_progress': 'status-progress',
		'completed': 'status-completed',
		'cancelled': 'status-cancelled'
	}
	return classMap[status] || ''
}

// 格式化订单时间
const formatOrderTime = (startTime: string, endTime: string) => {
	const formatTime = (timeStr: string) => {
		const date = new Date(timeStr)
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')
		return `${month}-${day} ${hours}:${minutes}`
	}

	return `${formatTime(startTime)} 至 ${formatTime(endTime)}`
}

// 获取空状态文本
const getEmptyText = () => {
	const textMap: Record<string, string> = {
		'all': '暂无订单',
		'pending_payment': '暂无待支付订单',
		'in_progress': '暂无进行中订单',
		'completed': '暂无已完成订单'
	}
	return textMap[currentTab.value] || '暂无订单'
}

// 加载订单列表
const loadOrders = async () => {
	loading.value = true
	try {
		// 根据当前筛选条件调用API
		const response = await getUserOrders({
			page: 1,
			limit: 50,
			status: currentTab.value === 'all' ? '' : currentTab.value
		})

		if (response.success) {
			orders.value = response.data.list || []
		} else {
			throw new Error(response.message || '获取订单失败')
		}
	} catch (error) {
		console.error('获取订单列表失败:', error)
		uni.showToast({
			title: '获取订单失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 查看订单详情
const viewOrderDetail = (order: any) => {
	console.log('查看订单详情:', order)
	// 跳转到订单详情页面
	uni.navigateTo({
		url: `/pages/order-detail/order-detail?orderId=${order.id}`
	})
}

// 取消订单
const cancelOrder = (order: any) => {
	uni.showModal({
		title: '确认取消',
		content: '确定要取消这个订单吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					// 显示取消中状态
					uni.showLoading({
						title: '取消中...',
						mask: true
					})

					// 调用取消订单API
					const response = await cancelParkingOrder(order.id)

					uni.hideLoading()

					if (response.success) {
						uni.showToast({
							title: '订单已取消',
							icon: 'success'
						})
						// 重新加载订单列表
						loadOrders()
					} else {
						throw new Error(response.message || '取消订单失败')
					}
				} catch (error) {
					uni.hideLoading()
					console.error('取消订单失败:', error)
					uni.showToast({
						title: '取消订单失败，请重试',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 支付订单
const payOrder = async (order: any) => {
	console.log('支付订单:', order)
	
	try {
		// 显示支付准备中状态
		uni.showLoading({
			title: '支付准备中...',
			mask: true
		})

		// 获取用户openid
		const openid = await getUserOpenid()

		uni.hideLoading()

		// 发起支付
		const payResult = await initiatePayment({
			orderId: order.id,
			openid: openid
		})

		if (payResult.success) {
			if (payResult.mock) {
				// 模拟支付成功
				uni.showToast({
					title: '模拟支付成功',
					icon: 'success'
				})
			} else {
				// 真实支付成功
				uni.showToast({
					title: '支付成功',
					icon: 'success'
				})
			}
			
			// 延迟重新加载订单列表，让用户看到成功提示
			setTimeout(() => {
				loadOrders()
			}, 1500)
			
		} else if (payResult.cancelled) {
			// 用户取消支付
			uni.showToast({
				title: '支付已取消',
				icon: 'none'
			})
		} else {
			// 支付失败
			uni.showToast({
				title: payResult.message || '支付失败',
				icon: 'error'
			})
		}

	} catch (error) {
		uni.hideLoading()
		console.error('支付过程出错:', error)
		
		// 显示详细错误信息
		const errorMessage = error.message || '支付失败，请重试'
		uni.showModal({
			title: '支付失败',
			content: errorMessage,
			showCancel: false,
			confirmText: '确定'
		})
	}
}

// 去预定
const goBooking = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

// 生命周期
onMounted(() => {
	console.log('订单页面加载完成')
	loadOrders()
})
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	background-color: #fff;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #eee;
}

.header-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.filter-tabs {
	background-color: #fff;
	display: flex;
	border-bottom: 1rpx solid #eee;
}

.tab-item {
	flex: 1;
	padding: 30rpx 20rpx;
	text-align: center;
	position: relative;
}

.tab-item.active {
	color: #007aff;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background-color: #007aff;
}

.tab-text {
	font-size: 28rpx;
}

.order-list {
	padding: 20rpx;
}

.order-item {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
}

.order-info {
	flex: 1;
}

.parking-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.order-number {
	font-size: 24rpx;
	color: #999;
	display: block;
}

.order-status {
	flex-shrink: 0;
}

.status-text {
	font-size: 26rpx;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-weight: 500;
}

.status-pending {
	background-color: #fff3cd;
	color: #856404;
}

.status-progress {
	background-color: #d1ecf1;
	color: #0c5460;
}

.status-completed {
	background-color: #d4edda;
	color: #155724;
}

.status-cancelled {
	background-color: #f8d7da;
	color: #721c24;
}

.order-details {
	margin-bottom: 20rpx;
}

.detail-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.detail-row:last-child {
	margin-bottom: 0;
}

.detail-label {
	color: #666;
	font-size: 28rpx;
}

.detail-value {
	color: #333;
	font-size: 28rpx;
}

.detail-value.price {
	color: #ff4757;
	font-weight: bold;
}

.detail-value.parking-type {
	font-weight: 500;
}

.detail-value.parking-type.indoor {
	color: #1890ff;
}

.detail-value.parking-type.outdoor {
	color: #fa8c16;
}

.order-actions {
	display: flex;
	gap: 20rpx;
	justify-content: flex-end;
}

.action-btn {
	padding: 16rpx 32rpx;
	border-radius: 8rpx;
	font-size: 26rpx;
	border: 1rpx solid;
}

.cancel-btn {
	background-color: #fff;
	color: #666;
	border-color: #ddd;
}

.pay-btn {
	background-color: #007aff;
	color: #fff;
	border-color: #007aff;
}

.empty-state {
	padding: 100rpx 40rpx;
	text-align: center;
}

.empty-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 40rpx;
}

.empty-text {
	color: #999;
	font-size: 28rpx;
}

.go-booking-btn {
	padding: 20rpx 40rpx;
	background-color: #007aff;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	font-size: 28rpx;
}

.loading-state {
	padding: 100rpx 40rpx;
	text-align: center;
}

.loading-text {
	color: #999;
	font-size: 28rpx;
}
</style>
